import axios from "axios";
import router from "umi/router";
import { Login,UserLogout } from '../../services/api';
import {message,Modal} from 'antd';

// 初始状态：本地缓存或空值对象
const isLogined = !localStorage.getItem('token');

export default {
	namespace: 'user',
	state: {
		isLogined:!isLogined,
		isShowGoogleAuthDialog:false
	},
	effects: {
		*login({ payload }, { call, put }) {
			payload.googleCode = payload.googleCode || '';
			const res = yield call(Login, payload);
			console.log(res);
			if(res.error){
				if(res.error == 'authcode_missing'){
					localStorage.setItem('googleType','login');
					
					localStorage.setItem('googleUserName',payload.email);
					localStorage.setItem('googlePassword',payload.password);
					yield put({ type: "showGoogleAuthDialog", payload: {isShowGoogleAuthDialog:true} });
				}
			}else{
				var data = res.data;
				if(payload.googleCode){
					localStorage.setItem('isNeedGoogleAuth',1);
				}else{
					localStorage.setItem('isNeedGoogleAuth',0);
				}
				localStorage.setItem("userinfo", JSON.stringify({email:payload.email}))
				localStorage.setItem("token", data.token)
				yield put({ type: "init", payload: {email:payload.email,isLogined:true} });
				localStorage.removeItem('googleType');
				localStorage.removeItem('googleUserName');
				localStorage.removeItem('googlePassword');
				message.success('登录成功');
				setTimeout(function(){
					router.push('/');
				},1000)
			}
		},
		*userLogout({ payload }, { call, put }) {
			const res = yield call(UserLogout);
			console.log(res);
			yield put({ type: "init", payload });
		},
	},
	reducers: {
		init(state, action) {
			console.log(action);
			return action.payload
		},
		showGoogleAuthDialog(state, action){
			const {isShowGoogleAuthDialog} = action.payload;
			console.log(action)
			return {...state,isShowGoogleAuthDialog};
		}
	}
};